package upload;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;

import db.DbUtils;
import filter.ImageResizer;

 public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		Session hbSession = null;
		try {
			long albumId = 0;
			String title = null;
			List items = upload.parseRequest(request);
			Iterator iter = items.iterator();
			FileItem item = null;
			HttpSession session = request.getSession();
			String fileName = null;
			String contentType = null;
			long fileSize = 0;
			while (iter.hasNext()) {
			    item = (FileItem) iter.next();
			    if (item.isFormField()) {
			    	if (item.getFieldName().equals("albumid")) {
			    		String aid = item.getString("UTF-8");
			    		albumId = Long.parseLong(aid);
			    	} else if (item.getFieldName().equals("title")) {
			    		title = item.getString("UTF-8");
			    	}
			    } else {
			    	fileName = item.getName();
					contentType = item.getContentType();
					fileSize = item.getSize();
			    }
			}
			//this lib sucks!
			String[] s = fileName.split("\\\\");
			fileName = s[s.length - 1];
		    if(contentType.equalsIgnoreCase("image/jpeg") || 
		    		contentType.equalsIgnoreCase("image/pjpeg") || /* stupid fix for the stupid IE */
		    		contentType.equalsIgnoreCase("image/png") || 
		    		contentType.equalsIgnoreCase("image/gif")) {
		    	if(fileSize < 5000000) {
		    		hbSession = DbUtils.startSession();
		    		if (title == null) {
		    			title = extractTitle(fileName);
		    		}
		    		String format = extractFormat(contentType);
		    		long pictureId = DbUtils.addPicture(hbSession, title, format, albumId, new Date());
		    		String fsName = pictureId + "." + format;
		    		String path = this.getServletContext().getInitParameter("IMAGES_DIRECTORY");
		    		path = this.getServletContext().getRealPath(path);
		    		File uploadedFile = new File(path + File.separatorChar + fsName);
				    item.write(uploadedFile);
				    ImageResizer resizer = new ImageResizer();
				    resizer.getThumbnails(path, fsName);
		    	} else {
		    		if(hbSession != null) {
				    	hbSession.getTransaction().rollback();
			    		hbSession.close();
			    	}
		    		response.sendRedirect("Error.jsp?msg=filesize");
		    		return;
		    	}
		    } else {
		    	if(hbSession != null) {
			    	hbSession.getTransaction().rollback();
		    		hbSession.close();
		    	}
		    	response.sendRedirect("Error.jsp?msg=filetype");
	    		return;
		    }
	    	if(hbSession != null) {
		    	hbSession.getTransaction().commit();
	    		hbSession.close();
	    	}
			response.sendRedirect("EnterInAlbumServlet?album_id=" + albumId);
			return;
		} catch (FileUploadException e) {
	    	if(hbSession != null) {
		    	hbSession.getTransaction().rollback();
	    		hbSession.close();
	    	}
			response.sendRedirect("Error.jsp?msg=fileupload");
		} catch (Exception e) {
	    	if(hbSession != null) {
		    	hbSession.getTransaction().rollback();
	    		hbSession.close();
	    	}
			response.sendRedirect("Error.jsp?msg=filewrite");
			e.printStackTrace();
		}
	}
	
	private String extractFormat(String contentType) {
		String format = null;
		if(contentType.equalsIgnoreCase("image/jpeg")) {
			format = "jpg";
		} else if(contentType.equalsIgnoreCase("image/png")) {
			format = "png";
		} else if(contentType.equalsIgnoreCase("image/pjpeg"))  {  /* stupid fix for the stupid IE */
			format = "jpg";
		} else {
			format = "gif";
		}
		return format;
	}

	private String extractTitle(String name) {
		int nameLen = name.length();
		name = name.substring(0, nameLen - 4);
		return name;
	}
}